﻿using DiverseStudents.Mods;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace DiverseStudents.Scripts
{
    internal class RecyclingListScript : UIBehaviour
    {
        /// <summary>
        /// 显示限制的最大行数
        /// </summary>
        public int showCount = 12;
        public float rowPadding = 10f;
        /// <summary>
        /// 数据项数
        /// </summary>
        public int rowCount = 0;
        /// <summary>
        /// 项的一行高度包含rowPaddding
        /// </summary>
        private float rowHeight;
       /// <summary>
       /// rect高度
       /// </summary>
        private float rectHeight;
        /// <summary>
        /// 显示项的开始索引
        /// </summary>
        private int childRowStart = 0;
        /// <summary>
        /// 数据项的开始索引
        /// </summary>
        private int childDataRowStart = 0;
        /// <summary>
        /// 预制体实际添加的项数
        /// </summary>
        private int childIteams = 0;

        ScrollRect scrollRect;
        Scrollbar scrollbar;
        ModsUIListItem[] scrollChildrens;
        RectTransform listGroupContent;
        RectTransform scrollTransform;
        /// <summary>
        /// 子物体位置类型
        /// </summary>
        enum ItemPosType
        {
            Top,
            Center,
            Bottom,
        }


        protected virtual new void  Awake()
        {
            scrollRect = GetComponent<ScrollRect>();
            scrollbar = scrollRect.GetComponentInChildren<Scrollbar>();
            scrollTransform = GetComponent<RectTransform>();
            listGroupContent = scrollRect.content.GetComponent<RectTransform>();
            if (scrollChildrens == null)
            {
                scrollChildrens = new ModsUIListItem[showCount];
            }
         
        }

        protected virtual new void OnEnable()
        {
            scrollRect.onValueChanged.AddListener(OnScrollRectChanged);
            scrollbar?.onValueChanged.AddListener(OnScrollbarChanged);
        }

        /// <summary>
        /// 刷新行高
        /// </summary>
        protected virtual new  void OnRectTransformDimensionsChange()
        {
            if (scrollTransform.sizeDelta.y > 0)
            {
                rectHeight = scrollTransform.sizeDelta.y;
                rowHeight  =  scrollTransform.sizeDelta.y /showCount;
            }
        }

        protected virtual new void OnDisable()
        {
            scrollRect.onValueChanged.RemoveListener(OnScrollRectChanged);
            scrollbar?.onValueChanged.RemoveListener(OnScrollbarChanged);
        }

        protected virtual void OnScrollRectChanged(Vector2 normalisedPos)
        {
            ReorganiseContent(false);
        }

        protected virtual void OnScrollbarChanged(float value)
        {
            ReorganiseContent(false);
        }


        /// <summary>
        /// 重新计算表内容
        /// </summary>
        /// <param name="clearContents">是否要清空列表</param>
        protected virtual void ReorganiseContent(bool clearContents)
        {
            if (rowHeight <= 0)
            {
                return;
            }
            if (clearContents)
            {
                scrollRect.StopMovement();
                scrollRect.verticalNormalizedPosition = 1;
            }
            int newRowStart = (int)(scrollRect.content.localPosition.y / rowHeight) -1;//下标从0开始
            int diff = newRowStart - childDataRowStart;//变化量
            if(diff >= childIteams)
            {
                childDataRowStart = newRowStart;
                childRowStart = 0;
                int rowIndex = newRowStart;
                foreach(var item in scrollChildrens)
                {
                    UpdateChild(item, rowIndex++);
                }
            }else if (diff != 0){
                int newBuffStart = (childRowStart +diff)%childIteams;
                if (diff < 0)//向上滑动
                {
                    for(int i = 0; i < -diff; i++)
                    {
                        int warpIndex = WrapChildIndex(childRowStart - i);
                        int rowIdx = childDataRowStart - i;
                        UpdateChild(scrollChildrens[warpIndex], rowIdx);
                    }
                }
                else //向下滑动
                {
                    int preLastIndex = childRowStart + childIteams - 1;
                    int preLastDataIndex = childDataRowStart + childIteams - 1;
                    for(int i = 0; i <= diff; i++)
                    {
                        int warpIndex = WrapChildIndex(preLastIndex - i);
                        int rowIdx = preLastDataIndex - i;
                        UpdateChild(scrollChildrens[warpIndex], rowIdx);
                    }
                }

                childDataRowStart = newRowStart;
                childRowStart = newBuffStart;
            }
        }

        protected virtual void UpdateChild(ModsUIListItem item,int rowIdx)
        {
            if(rowIdx < 0 || rowIdx > childIteams)
            {
                item.gameObject.SetActive(false);
            }
            else
            {
                var childRect = item.rectTransform.rect;
                Vector2 pivot = item.rectTransform.pivot;
                float ypos = rowHeight * rowIdx + (1- pivot.y)* childRect.height;
                float xpos = pivot.x * childRect.width;
                item.rectTransform.anchoredPosition = new Vector2(xpos, ypos);

                item.gameObject.SetActive(true);
            }
        }

        private int WrapChildIndex(int idx)
        {
            return (idx % childIteams + childIteams)%childIteams;
        }



        private void RefershContenSize()
        {
            if (rowHeight > 0)
            {
                 float height = rowHeight* rowCount;
                listGroupContent.sizeDelta = new Vector2(listGroupContent.sizeDelta.x, height);
            }
        }

        #region 外部接口
        public void AddItem()
        {
            var name = ModCreate.GetFileName();
            var mod = new ModArchive
            {
                id = name,
                name = name,
                description = "测试模组",
                check = true,
            };
            if (childIteams < showCount)
            {
                new ModsUIListItem(mod, showCount, listGroupContent, SelectMod);
                childIteams++;
            }
            //modArchives.AddLast(mod);
            RefershContenSize();
        }

        public void RemoveItem()
        {

        }
        #endregion

        public void SelectMod()
        {

        }

        private void StopMove()
        {
            scrollRect.StopMovement();
        }

        protected virtual new void  OnDestroy() { }
    }
}

